""" Точка входа программы """
import argparse
import logging
from pprint import pprint

from buondua.models import db, MODELS
from buondua.scrappers.picture import PictureParser
from buondua.scrappers.album import AlbumParser

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

parser = argparse.ArgumentParser(
                    prog='buondua',
                    description='Scrapper for buondua.com',
                    epilog='...')
parser.add_argument('--save',
                    dest='do_save',
                    action='store_true',
                    help='Do save result to database?')
parser.add_argument('--print',
                    dest='do_print',
                    action='store_true',
                    help='Do print result to screen?')

# Subparsers
subparsers = parser.add_subparsers(title='Commands',
                                   required=True,
                                   dest='command')

get_parser = subparsers.add_parser('get',
                                   help='Use a parser to collect an album once')
get_parser.add_argument('url',
                        type=str,
                        help='A URL to album')

collect_parser = subparsers.add_parser('collect',
                                       help='Collect albums from collection (tags, "hot", eg.)')
collect_parser.add_argument('url',
                            type=str,
                            help='A URL to collection of albums')
collect_parser.add_argument('--recursive',
                            dest='do_recursive',
                            action='store_true',
                            help='Do recursive parse albums?')
collect_parser.add_argument('--limit',
                            type=int,
                            default=-1,
                            dest='limit',
                            help='A parsing limit')


def health_check_database():
    logging.debug('Database check')
    db.execute_sql('SELECT 1;')
    db.execute_sql('SELECT 1 FROM album;')
    db.execute_sql('SELECT 1 FROM picture;')


def run_album_parsing(args):
    '''Запуск парсинга альбома'''
    logging.debug('run_album_parsing started')
    picture_parser = PictureParser()
    data = picture_parser.parse(args.url, do_save=args.do_save)
    if args.do_print:
        pprint(data)


def run_collection_parsing(args):
    '''Запуск парсинга колекции, извлечение альбомов и, возможно (do_recursive), рекурсивный парсинг их'''
    logging.debug('run_collection_parsing started')

    album_parser = AlbumParser()
    data = album_parser.parse(args.url)

    if args.do_print:
        pprint(data)

    albums = data.pop('albums')
    logging.debug('albums:', albums)

    if args.do_recursive:
        limit = args.limit if args.limit >= 0 else len(albums)
        logging.warning('run_collection_parsing: limit == 0')

        for url in albums[:limit]:
            picture_parser = PictureParser()
            data = picture_parser.parse(url, do_save=args.do_save)

            if args.do_print:
                pprint(data)


def main():
    try:
        args = parser.parse_args()
        logging.debug(args)

        if args.do_save:
            db.connect(reuse_if_open=True)
            db.create_tables(MODELS)
            health_check_database()
            logging.info('Database initialized.')

        if args.command == 'get':
            run_album_parsing(args)
        if args.command == 'collect':
            run_collection_parsing(args)

    except Exception as e:
        logging.error(e)
    except BaseException as e:
        logging.error(e)
    finally:
        if not db.is_closed():
            db.close()
            logging.debug('Database was closed.')


if __name__ == '__main__':
    logging.debug('Start program.')
    main()
    logging.debug('Exit program.')
